package com.itheima;

import com.itheima.bean.Stock;
import com.itheima.lock.DbLock;
import com.itheima.lock.RedisLock;
import com.itheima.lock.ZkLock;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StockMain {
    //private  static Lock lock=new ReentrantLock();
    @Autowired
    private static DbLock dbLock;
    private static RedisLock redisLock;
    private static RLock mylock;
    private static ZkLock zkLock;

    static {
        ClassPathXmlApplicationContext classPathXmlApplicationContext= new ClassPathXmlApplicationContext("applicationContext.xml") ;
        dbLock=classPathXmlApplicationContext.getBean(DbLock.class);
        redisLock=classPathXmlApplicationContext.getBean(RedisLock.class);
       /*
        Config config=new Config();
        config.useSingleServer().setAddress("redis://192.168.157.128:6379").setPassword("123456").setDatabase(0);
        Redisson  redisson=(Redisson)Redisson.create(config);
        mylock=redisson.getLock("redis_lock_stock");*/

        zkLock=new ZkLock("192.168.157.128:2181","stock_zk");
    }

    static  class StockThread implements  Runnable{
        public void run() {
            //上锁
           // lock.lock();
            //dbLock.lock();
            //redisLock.lock();
            //mylock.lock();
            zkLock.lock();
            //调用减少库存的方法
            boolean b=new Stock().reduceStock();
            //解锁
            //lock.unlock();
            //dbLock.unlock();
            //redisLock.unlock();
            //mylock.unlock();
            zkLock.unlock();
            if(b)
            {
                System.out.println(Thread.currentThread().getName()+"减少库存成功");
            }else
            {
                System.out.println(Thread.currentThread().getName()+"减少库存失败");
            }
        }
    }


    public  static void main(String[] args)
    {
        new Thread(new StockThread(),"线程1").start();
        new Thread(new StockThread(),"线程2").start();
    }
}
